'use client'
import React, { useState, useEffect } from 'react'
import Image from 'next/image'
import { Skeleton, Alert, Empty, Pagination, Breadcrumb, Button } from 'antd'
import { useRouter, useSearchParams } from 'next/navigation'
import { createStyles } from 'antd-style'

import { userCenterGet7, userCenterGet6 } from '@/apis'
import SearchBar from '@/components/SearchBar'

// 定义接口返回的数据结构
interface ItemPoint {
  id: number
  itemName: string
  itemContent: string
  categoryId?: number
  categoryName?: string
}

interface CategoryItem {
  id: number
  categoryName: string
}

// 自定义样式
const useStyle = createStyles(({ prefixCls, css }) => ({
  // 面包屑容器
  breadcrumbContainer: css`
    margin-bottom: 16px;
    width: 100%;
  `,
  // 分页容器
  paginationContainer: css`
    margin-top: 24px;
    width: 100%;
    display: flex;
    justify-content: center;
  `,
  // 分类按钮样式
  categoryButton: css`
    position: relative;
    border-radius: 4px;
    transition: all 0.3s ease;

    &.${prefixCls}-btn {
      background: #fff;
      color: #333;
      border: 1px solid #d9d9d9;
      margin-right: 8px;

      &:hover:not([disabled]) {
        border-color: #2570ff;
        color: #2570ff;
        background: #f0f7ff;
      }
    }
  `,
  categoryButtonActive: css`
    &.${prefixCls}-btn {
      background: linear-gradient(135deg, #2570ff, #1890ff);
      color: #fff;
      border: none;
      box-shadow: 0 2px 8px rgba(24, 144, 255, 0.3);
      margin-right: 8px;

      &:hover:not([disabled]) {
        box-shadow: 0 4px 12px rgba(24, 144, 255, 0.4);
        background: linear-gradient(135deg, #1890ff, #096dd9);
      }
    }
  `,
  // 分类容器
  categoryContainer: css`
    margin: 16px 0;
    display: flex;
    flex-wrap: wrap;
    gap: 8px;
  `,
}))

export default function Pdp() {
  const router = useRouter()
  const searchParams = useSearchParams()
  const { styles } = useStyle()

  // 状态管理
  const [itemPointList, setItemPointList] = useState<ItemPoint[]>([])
  const [categories, setCategories] = useState<CategoryItem[]>([])
  const [loading, setLoading] = useState(false)
  const [categoryLoading, setCategoryLoading] = useState(false)
  const [error, setError] = useState<string | null>(null)
  const [categoryError, setCategoryError] = useState<string | null>(null)
  const [currentPage, setCurrentPage] = useState(1)
  const [totalItems, setTotalItems] = useState(0)
  const [pageSize] = useState(20)
  const [currentCategory, setCurrentCategory] = useState('all')
  const [searchKeyword, setSearchKeyword] = useState('')

  // 从URL参数初始化状态
  useEffect(() => {
    const category = searchParams.get('condition.category') || 'all'
    const keyword = searchParams.get('condition.keyword') || ''
    const page = parseInt(searchParams.get('condition.page') || '1', 10)

    setCurrentCategory(category)
    setSearchKeyword(keyword)
    setCurrentPage(page)
  }, [searchParams])

  // 获取分类数据
  const fetchCategories = async () => {
    setCategoryLoading(true)
    setCategoryError(null)
    try {
      const response = await userCenterGet6({
        baseURL: '/api/proxy',
      })
      setCategories(
        Array.isArray(response?.data?.data) ? response.data.data : [],
      )
    } catch (err) {
      setCategoryError('获取分类失败')
      console.error('分类请求错误:', err)
    } finally {
      setCategoryLoading(false)
    }
  }

  // 获取检测项点数据
  const fetchItemPoints = async () => {
    setLoading(true)
    setError(null)
    try {
      // 构建符合接口要求的参数
      const params = {
        // 分页参数
        'condition.page': currentPage,
        'condition.size': pageSize,

        // 分类参数 - 关键修复：使用接口要求的 condition.categoryId
        'condition.categoryId':
          currentCategory !== 'all' ? Number(currentCategory) : undefined,

        // 搜索参数
        'condition.itemName': searchKeyword.trim() || undefined,

        // 可以根据需要添加热门筛选
        // 'condition.isPopular': false
      }

      // 过滤掉 undefined 的参数
      const filteredParams = Object.fromEntries(
        Object.entries(params).filter(([_, value]) => value !== undefined),
      )

      const queryString = new URLSearchParams(
        Object.entries(filteredParams).reduce((acc, [key, value]) => {
          acc[key] = String(value)
          return acc
        }, {} as Record<string, string>),
      ).toString()

      const response = await userCenterGet7({
        url: `/user_center/item_point?${queryString}`,
        baseURL: '/api/proxy',
      })

      setItemPointList(response?.data?.data.data || [])
      setTotalItems(response?.data?.data.total || 0)
    } catch (err) {
      setError('网络异常，无法加载检测项点数据')
      console.error('检测项点请求错误:', err)
    } finally {
      setLoading(false)
    }
  }

  // 监听依赖变化，重新加载数据
  useEffect(() => {
    fetchCategories()
  }, [])

  useEffect(() => {
    fetchItemPoints()
  }, [currentPage, currentCategory, searchKeyword])

  // 分页处理函数
  const handlePageChange = (page: number) => {
    setCurrentPage(page)
    // 更新URL参数
    const params = new URLSearchParams(searchParams)
    params.set('condition.page', page.toString())
    router.push(`/inspection?${params.toString()}`)
    window.scrollTo({ top: 0, behavior: 'smooth' })
  }

  // 分类切换处理
  const handleCategoryChange = (categoryId: string) => {
    setCurrentCategory(categoryId)
    setCurrentPage(1)
    // 更新URL参数
    const params = new URLSearchParams(searchParams)
    params.set('condition.category', categoryId)
    params.set('condition.page', '1')
    router.push(`/inspection?${params.toString()}`)
    window.scrollTo({ top: 0, behavior: 'smooth' })
  }

  // 搜索处理（从SearchBar接收）
  const handleSearch = (value: string) => {
    setSearchKeyword(value)
    setCurrentPage(1)
    // 更新URL参数
    const params = new URLSearchParams(searchParams)
    if (value.trim()) {
      params.set('condition.keyword', value.trim())
    } else {
      params.delete('condition.keyword')
    }
    params.set('condition.page', '1')
    router.push(`/inspection?${params.toString()}`)
  }

  // 构建面包屑
  const getBreadcrumbItems = () => {
    return [
      {
        title: (
          <span onClick={() => router.push('/')} className="cursor-pointer">
            首页
          </span>
        ),
        key: 'home',
      },
      {
        title: (
          <span
            onClick={() => router.push('/inspection')}
            className="cursor-pointer"
          >
            检测项点
          </span>
        ),
        key: 'inspection',
        isCurrent: true,
      },
    ]
  }

  // 渲染分类按钮
  const renderCategoryButtons = () => {
    if (categoryLoading) {
      return (
        <div className="flex gap-2">
          {[1, 2, 3, 4].map(i => (
            <Skeleton.Button key={i} size="default" style={{ width: 80 }} />
          ))}
        </div>
      )
    }

    if (categoryError) {
      return (
        <Alert
          message={categoryError}
          type="error"
          showIcon
          style={{ marginBottom: 16 }}
        />
      )
    }

    // 始终显示"全部"分类
    const allCategories = [{ id: 'all', categoryName: '全部' }, ...categories]

    return allCategories.map(category => (
      <Button
        key={category.id}
        onClick={() => handleCategoryChange(category.id.toString())}
        className={
          currentCategory === category.id.toString()
            ? styles.categoryButtonActive
            : styles.categoryButton
        }
        disabled={loading}
      >
        {category.categoryName}
      </Button>
    ))
  }

  // 渲染单个检测项
  const renderItemPoint = (item: ItemPoint) => {
    return (
      <div
        key={item.id}
        className="bg-white shadow-md flex flex-col items-center justify-center hover:shadow-lg transition-shadow duration-300"
      >
        <h3 className="w-full text-lg font-bold mb-2 text-center text-[#000] p-4 bg-[url('/images/hotTitleBg.png')] bg-no-repeat bg-cover">
          {item.itemName || '未命名'}
        </h3>
        <p className="text-[#606F85] p-6 leading-6 h-40 overflow-hidden">
          {item.itemContent || '暂无描述'}
        </p>
      </div>
    )
  }

  // 渲染网格
  const renderItemPointList = () => {
    if (loading) {
      return Array(pageSize)
        .fill(0)
        .map((_, idx) => (
          <div
            key={idx}
            className="bg-white shadow-md flex flex-col items-center justify-center"
          >
            <Skeleton active paragraph={{ rows: 1 }} className="w-full p-4" />
            <Skeleton active paragraph={{ rows: 2 }} className="p-6" />
          </div>
        ))
    }

    if (error) {
      return (
        <div className="col-span-full flex justify-center items-center py-10">
          <Alert message={error} type="error" showIcon />
        </div>
      )
    }

    if (itemPointList.length === 0) {
      return (
        <div className="col-span-full flex justify-center items-center py-10">
          <Empty description="暂无检测项点内容" />
        </div>
      )
    }

    return itemPointList.map(renderItemPoint)
  }

  return (
    <section>
      <div className="container mx-auto flex flex-col my-4 md:flex-col items-center justify-between h-full">
        {/* 面包屑 */}
        <div className={styles.breadcrumbContainer}>
          <Breadcrumb items={getBreadcrumbItems()} separator=">" />
        </div>

        {/* 搜索框 */}
        <SearchBar
          width={600}
          targetPath="/inspection"
          placeholder="搜索检测项点..."
          clearAfterSearch={false}
          onSearch={handleSearch}
        />

        <div className="w-full my-2">
          <div className={styles.categoryContainer}>
            {renderCategoryButtons()}
          </div>
        </div>

        {/* 检测项点网格 */}
        <div className="w-full grid gap-4 md:grid-cols-2 xl:grid-cols-4">
          {renderItemPointList()}
        </div>

        {/* 分页组件 */}
        {!loading && !error && totalItems > 0 && (
          <div className={styles.paginationContainer}>
            <Pagination
              current={currentPage}
              pageSize={pageSize}
              total={totalItems}
              onChange={handlePageChange}
              showSizeChanger={false}
              showQuickJumper
              showTotal={total => `共 ${total} 条`}
            />
          </div>
        )}
      </div>
    </section>
  )
}
